package com.xjtu.se.homework.ops.result.controller;

import com.xjtu.se.homework.client.FileProperties;
import com.xjtu.se.homework.common.Constants;
import com.xjtu.se.homework.common.Result;
import com.xjtu.se.homework.ops.result.service.ResultService;
import com.xjtu.se.homework.ops.result.dto.SearchDto;
import com.xjtu.se.homework.ops.result.bean.ResultContent;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Base64;

@RestController
@RequestMapping("/ops/result")
public class ResultAPI {
    @Resource
    private ResultService resultService;

    @PostMapping("/getContent")
    public Result getContent(@RequestBody SearchDto dto) {
        ArrayList<ResultContent> list = resultService.getContent(dto); // 只有一条
        ResultContent resultContent = new ResultContent();
        if (list.size() != 0) {
            resultContent = list.get(0);
        }else{
            return null;
        }
        if (resultContent.getSearch_image() != null) {
            String search_image = "D:/project/homework_helper/helper-springboot/uploads/" +resultContent.getSearch_image();
            FileInputStream in = null;
            ByteArrayOutputStream bos = null;
            try {
                File file = new File(search_image);
                if (!file.exists()) {
                    throw new Exception("图片不存在");
                }
                in = new FileInputStream(search_image);
                bos = new ByteArrayOutputStream();
                byte[] b = new byte[1024];
                int len = -1;
                while((len = in.read(b)) != -1) {
                    bos.write(b, 0, len);
                }
                byte[] fileByte = bos.toByteArray();
                Base64.Encoder encoder = Base64.getEncoder();
                String image = encoder.encodeToString(fileByte);
                resultContent.setSearch_image(image);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return Result.success("success", resultContent);
    }
}

